package com.hippsomhapp.rememberthemilk;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

import com.mdt.rtm.ApplicationInfo;
import com.mdt.rtm.ServiceException;
import com.mdt.rtm.ServiceImpl;
import com.mdt.rtm.ServiceInternalException;
import com.mdt.rtm.data.RtmAuth;
import com.mdt.rtm.data.RtmAuth.Perms;


public class rememberthemilk extends Activity {
	
	private static final String API_KEY = "1f1571dc20782dbc2d9722627707c4e4";
	private static final String API_SHARED_SECRET = "b298f472de8ca573";
	private static final String API_NAME = "remindroid";
	
	private ServiceImpl servImpl = null;
	String authUrl;
	WebView webview;
	Button button;
	String authToken;
	RtmAuth rtmAuth;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstance) {
        super.onCreate(savedInstance);
		this.setContentView(R.layout.main);

        ApplicationInfo rtmApp = new ApplicationInfo(API_KEY, API_SHARED_SECRET, API_NAME);       
        
        try {
			servImpl = new ServiceImpl(rtmApp);
				
			authUrl = servImpl.beginAuthorization(Perms.delete);
			
//			Intent intent = new Intent(Intent.ACTION_VIEW,
//                    Uri.parse(authUrl));
//            startActivity(intent);
			
			webview = (WebView) findViewById(R.id.webview);
			webview.setWebViewClient(new MyWebViewClient());
//			webview.getSettings().setJavaScriptEnabled(true);
			webview.loadUrl(authUrl);

            button = (Button) findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                	try {
						authToken = servImpl.completeAuthorization();
						Toast t = Toast.makeText(rememberthemilk.this, authToken, Toast.LENGTH_LONG);
			            t.show();
					} catch (ServiceException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }
            });
            
            rtmAuth = servImpl.auth_checkToken(authToken);
            
 			
		} catch (ServiceInternalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
    private class MyWebViewClient extends WebViewClient {
    	@Override
    	public boolean shouldOverrideUrlLoading(WebView view, String url){
    		view.loadUrl(url);
    		return true;
    	}
    	
    }

}

